package com.sport.service.impl;

import com.sport.bean.Admin;
import com.sport.bean.PageParam;
import com.sport.dao.IAdminDao;
import com.sport.service.IAdminService;
import com.sport.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Author wxq
 * @Date 2021/5/8
 **/
@Service
public class AdminServiceImpl implements IAdminService {


    @Autowired
    private IAdminDao adminDao;

    @Override
    public JsonResult adminLogin(String username, String password, String captcha, HttpSession session) {
        //校验验证码
        String captchaSession = (String) session.getAttribute("captcha");
        if (!captchaSession.equalsIgnoreCase(captcha)) {
            return JsonResult.error("验证码错误");
        }
        Admin admin = findByName(username);
        if (admin == null) {
            return JsonResult.error("用户名不存在");
        }
        if (!admin.getPassword().equals(password)) {
            return JsonResult.error("密码错误");
        }
        //将管理员信息保存在session中
        session.setAttribute("admin", admin);
        return JsonResult.ok("登陆成功");
    }

    @Override
    public List<Admin> listPage(PageParam<Admin> pageParam) {
        return adminDao.listPage(pageParam);
    }



    @Override
    public Admin findByName(String username) {
        return adminDao.findByName(username);
    }

    @Override
    public Admin findById(Integer id) {
        return adminDao.findById(id);
    }

    @Override
    public JsonResult updatePwd(String username, String oldPwd, String newPwd) {
        Admin admin = findByName(username);
        if (!admin.getPassword().equals(oldPwd)) {
            return JsonResult.error("旧密码错误，请重新输入");
        }

        int i = adminDao.updatePwd(newPwd, username);
        if (i > 0) {

            return JsonResult.ok("修改成功");

        } else {
            return JsonResult.error("修改失败");
        }

    }

    @Override
    public int updateInfo(Admin admin) {
        return adminDao.updateAdmin(admin);
    }

    @Override
    public int addAdmin(Admin admin) {
        return adminDao.addAdmin(admin);
    }

    @Override
    public int deleteAdmin(Integer id) {
        return adminDao.deleteAdmin(id);
    }
}
